<?php

namespace Common\Model;

class BookAuthorModel extends XuecheModel {

    protected $pk = 'author_id';
    protected $tableName = 'book_author';
    protected $fields = array(
            'author_id', 'name','age','sex','image_id','intro','img'
        );

    /**
     * 清空数据缓存
     *
     */
    public function ClearAllCache() {

    }

    //缓存设置
    protected $_useCacheType = 'file';
    protected $_catheTime = 0;

    public function Validate($data) {
        if(empty($data['name'])){
            return FALSE;
        }
        return TRUE;
    }

    public function getAuthorName($author_id){
        if(empty($author_id)){            return FALSE;}
        $name = $this->where("`{$this->pk}` = '{$author_id}'")->field('name')->find();
        if(empty($name['name'])){
            return FALSE;
        }
        return $name['name'];

    }

    /**
     * 获取作者ID 否则新增作者信息
     * @param type $name
     * @return boolean
     */
    public function getAuthorId($name){
        if(empty($name)) return FALSE;
        $id = $this->where("`name` = '{$name}'")->field('author_id')->find();
        if($id['author_id'] > 0){
            return $id['author_id'];
        }else{
            return $this->saveAuthor(array('name'=>$name));
        }

    }

    /**
     * 新增和修改作者信息
     * @param type $data
     * @return boolean
     */
    private function saveAuthor($data){
        if($this->Validate($data)){
            if(empty($data[$this->pk])){
                return $this->add($data);
            }else{
                return $this->save($data);
            }
        }
        return FALSE;
    }




}
